package com.wise.blockingque.delayqueue;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class DelayQueueTest {
    public static void main(String[] args) {
        //创建延时队列
        DelayQueue<Message> queue = new DelayQueue<>();
        //添加延时消息 m1 延时 3s
        Message m1 = new Message(1, "world", 3000);
        //添加延时消息 m2 延时 10s
        Message m2 = new Message(2, "hello", 10000);
        //将延时消息放到延时队列中
        queue.offer(m2); //注：这里先放的m2
        queue.offer(m1);
        //启动消费线程 消费添加到延时队列中的消息，前提是任务到了延时时间
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(new Consumer(queue));
        executor.shutdown();
        try {
            while (!executor.awaitTermination(2, TimeUnit.SECONDS)) {
                System.out.println("任务执行中!");
            }
            System.out.println("finished!!!!!!!!!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
